using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Common
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class Appsettings
    {
        static IConfiguration Configuration{get;set;}
        static Appsettings()
        {
            string path = "appsettings.json";
            if(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT").ToString().ToUpper() == ("Development").ToUpper())
            {
                path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
            }
            Console.WriteLine(path);
            //ReloadOnChange = true; 当appsettings.json被修改时重新加载
            Configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())////这样的话，可以直接读目录里的json文件，而不是 bin 文件夹下的，所以不用修改复制属性
                .Add(new JsonConfigurationSource{Path = path,Optional = false,ReloadOnChange=true}).Build();
        }

        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static string app(params string[] sections)
        {
            try
            {
                var reval = string.Empty;
                for(int i =0;i < sections.Length;i++)
                {
                    reval += sections[i]+":";
                }
                Console.WriteLine(reval);
                return Configuration[reval.TrimEnd(':')];
            }
            catch
            {
                return "";
            }
        }
    }
}
